package momo.app.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileCreator
{
	static final String DEFAULT_DIRECTORY = "jackson_logs";
	private String filename;
	private SimpleDateFormat format;
	
	private String directoryUsed;
	
	public FileCreator(String filename, String directoryUsed)
	{
		this.filename = filename;
		this.directoryUsed = directoryUsed;
		format = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss,SSS]");
	}
	
	public FileCreator(String filename)
	{
		this(filename, DEFAULT_DIRECTORY);
	}
	
	public void setDirectoryUsed(String directoryUsed)
	{
		this.directoryUsed = directoryUsed;
	}
	
	public synchronized void logToFile(String contents)
	{
		try {
			File directory = new File(this.directoryUsed);
			
			if ( !directory.exists() )
				directory.mkdir();
			else if ( !directory.isDirectory() )
				directory.mkdir();
			
			FileWriter out = new FileWriter(directory.getName()+File.separator+filename, true);
			out.write(getDate()+" - " + contents + "\n");
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private String getDate()
	{
		return format.format(new Date());		
	}
}//end of class FileCreator
